/**
 * 多模型调试面板
 * 用于测试和调试多模型功能
 */

import React, { useState, useEffect } from 'react';
import { Card, Button, List, Tag, Alert, Spin, Typography, Space, Input, Select } from 'antd';
import { BugOutlined, ReloadOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { simpleMultiModelService } from '../../services/simple-multi-model.service';
import ModelListTest from './ModelListTest';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

export const MultiModelDebugPanel: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [models, setModels] = useState<string[]>([]);
  const [modelInfos, setModelInfos] = useState<Map<string, any>>(new Map());
  const [error, setError] = useState<string | null>(null);
  const [testPrompt, setTestPrompt] = useState('请写一篇关于人工智能发展的短文');
  const [selectedModels, setSelectedModels] = useState<string[]>([]);
  const [testResults, setTestResults] = useState<any[]>([]);
  const [testing, setTesting] = useState(false);

  const loadModelConfigs = async () => {
    setLoading(true);
    setError(null);
    
    try {
      console.log('🔍 开始加载模型配置...');
      
      // 测试直接调用API
      const response = await fetch('http://localhost:8002/api/v1/model-configs');
      console.log('📡 API响应状态:', response.status);
      
      if (response.ok) {
        const configs = await response.json();
        console.log('📋 获取到的模型配置:', configs);
      } else {
        console.warn('⚠️ API调用失败，状态码:', response.status);
      }
      
      // 通过服务获取模型列表
      const availableModels = await simpleMultiModelService.getAvailableModels();
      console.log('🎯 服务返回的可用模型:', availableModels);
      setModels(availableModels);
      
      // 获取每个模型的详细信息
      const infos = new Map();
      for (const modelId of availableModels) {
        const info = await simpleMultiModelService.getModelInfo(modelId);
        if (info) {
          infos.set(modelId, info);
        }
      }
      setModelInfos(infos);
      
      // 默认选择前两个模型
      if (availableModels.length > 0) {
        setSelectedModels(availableModels.slice(0, Math.min(2, availableModels.length)));
      }
      
    } catch (err) {
      console.error('❌ 加载模型配置失败:', err);
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setLoading(false);
    }
  };

  const testMultiModelGeneration = async () => {
    if (selectedModels.length === 0 || !testPrompt.trim()) {
      return;
    }

    setTesting(true);
    setTestResults([]);
    
    try {
      console.log('🚀 开始多模型测试...');
      const results = await simpleMultiModelService.compareModels(testPrompt, selectedModels);
      console.log('📊 测试结果:', results);
      setTestResults(results);
    } catch (err) {
      console.error('❌ 多模型测试失败:', err);
      setError(err instanceof Error ? err.message : '测试失败');
    } finally {
      setTesting(false);
    }
  };

  useEffect(() => {
    loadModelConfigs();
  }, []);

  return (
    <div style={{ padding: 16 }}>
      {/* 模型列表诊断 */}
      <ModelListTest />
      
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <BugOutlined />
            <span>多模型调试面板</span>
          </div>
        }
        extra={
          <Button 
            icon={<ReloadOutlined />} 
            onClick={loadModelConfigs}
            loading={loading}
          >
            重新加载
          </Button>
        }
      >
        {error && (
          <Alert
            message="错误信息"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        {loading ? (
          <div style={{ textAlign: 'center', padding: 40 }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>
              <Text type="secondary">正在加载模型配置...</Text>
            </div>
          </div>
        ) : (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* 模型列表 */}
            <div>
              <Title level={5}>可用模型 ({models.length})</Title>
              <List
                dataSource={models}
                renderItem={(modelId) => {
                  const modelInfo = modelInfos.get(modelId);
                  return (
                    <List.Item>
                      <List.Item.Meta
                        title={
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span>{modelInfo?.name || modelId}</span>
                            {modelInfo?.provider && (
                              <Tag color="blue">{modelInfo.provider}</Tag>
                            )}
                            {modelInfo?.status && (
                              <Tag color={modelInfo.status === 'active' ? 'green' : 'orange'}>
                                {modelInfo.status}
                              </Tag>
                            )}
                          </div>
                        }
                        description={
                          <div>
                            <div><strong>ID:</strong> {modelId}</div>
                            {modelInfo?.description && (
                              <div><strong>描述:</strong> {modelInfo.description}</div>
                            )}
                          </div>
                        }
                      />
                    </List.Item>
                  );
                }}
              />
            </div>

            {/* 测试区域 */}
            <div>
              <Title level={5}>多模型测试</Title>
              
              <div style={{ marginBottom: 16 }}>
                <Text strong>选择测试模型：</Text>
                <Select
                  mode="multiple"
                  style={{ width: '100%', marginTop: 8 }}
                  placeholder="选择要测试的模型"
                  value={selectedModels}
                  onChange={setSelectedModels}
                >
                  {models.map(modelId => {
                    const modelInfo = modelInfos.get(modelId);
                    return (
                      <Option key={modelId} value={modelId}>
                        {modelInfo?.name || modelId}
                      </Option>
                    );
                  })}
                </Select>
              </div>

              <div style={{ marginBottom: 16 }}>
                <Text strong>测试提示词：</Text>
                <TextArea
                  rows={3}
                  value={testPrompt}
                  onChange={(e) => setTestPrompt(e.target.value)}
                  placeholder="输入测试提示词..."
                  style={{ marginTop: 8 }}
                />
              </div>

              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={testMultiModelGeneration}
                loading={testing}
                disabled={selectedModels.length === 0 || !testPrompt.trim()}
              >
                开始测试
              </Button>
            </div>

            {/* 测试结果 */}
            {testResults.length > 0 && (
              <div>
                <Title level={5}>测试结果</Title>
                <List
                  dataSource={testResults}
                  renderItem={(result) => (
                    <List.Item>
                      <Card
                        title={
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span>{result.modelName}</span>
                            {result.error ? (
                              <Tag color="red">失败</Tag>
                            ) : (
                              <Tag color="green">成功</Tag>
                            )}
                          </div>
                        }
                        size="small"
                        style={{ width: '100%' }}
                      >
                        {result.error ? (
                          <Alert
                            message="生成失败"
                            description={result.error}
                            type="error"
                            showIcon
                          />
                        ) : (
                          <div>
                            <div style={{ marginBottom: 8 }}>
                              <Text strong>响应时间：</Text> {result.duration}ms
                            </div>
                            <div style={{ marginBottom: 8 }}>
                              <Text strong>生成内容：</Text>
                            </div>
                            <div style={{ 
                              background: '#f5f5f5', 
                              padding: 12, 
                              borderRadius: 4,
                              maxHeight: 200,
                              overflow: 'auto'
                            }}>
                              {result.content || '无内容'}
                            </div>
                          </div>
                        )}
                      </Card>
                    </List.Item>
                  )}
                />
              </div>
            )}
          </Space>
        )}
      </Card>
    </div>
  );
};

export default MultiModelDebugPanel;
